package main.orga;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import main.util.JdbcUtil;

public class QueryOrgainfoForTree {

	static JdbcUtil jdbcUtil;
	public static void main(String[] args) {
		jdbcUtil = new JdbcUtil();
		String sql = "SELECT DISTINCT(old_orgaId)  FROM t_kfrh_staffinfo_gx";
		System.out.println(sql);
		List<Map<String, Object>> orgaInfoList = jdbcUtil.queryForList(sql);
		List<Map<String, Object>> allOrgaInfoList = new ArrayList<Map<String,Object>>();
		if (!orgaInfoList.isEmpty()) {
			allOrgaInfoList = querySuperOrgaInfo(orgaInfoList);
			
		}
		
		if (!allOrgaInfoList.isEmpty()) {
			//过滤有用的组织机构数据
			initOrgaInfoForTree(allOrgaInfoList);
		}
		
	}
	private static void initOrgaInfoForTree(
			List<Map<String, Object>> allOrgaInfoList) {
		//拼接查询条件
		String orgaIds ="''";
		for (Map<String, Object> orgaInfo:allOrgaInfoList) {
			if (orgaInfo.get("old_orgaId")!=null) {
				orgaIds = orgaIds + ",'" +orgaInfo.get("old_orgaId")+"'";
			}else {
				orgaIds = orgaIds + ",'" +orgaInfo.get("old_superorgaId")+"'";
			}
		}
		String tableName = "t_kfrh_orgainfo_gx";
//		String tableName = "t_kfrh_orgainfo_gx_zhuijia_"+"20170421";
//		jdbcUtil = new JdbcUtil();
//		String dropTable = "drop table if exists "+tableName;
//		jdbcUtil.update(dropTable);
//		jdbcUtil = new JdbcUtil();
//		String newTableSql ="CREATE TABLE "+tableName+ " LIKE t_kfrh_orgainfo_gx";
//		jdbcUtil.update(newTableSql);
		
		jdbcUtil = new JdbcUtil();
		String initOrgaInfo ="INSERT into "+tableName+" SELECT * FROM t_kfrh_orgainfo_gx_zhuijia WHERE old_orgaId in("+orgaIds+")";
		jdbcUtil.update(initOrgaInfo);
	}
	private static List<Map<String, Object>> querySuperOrgaInfo(
			List<Map<String, Object>> orgaInfoList) {
		List<Map<String, Object>> allOrgaInfoList = orgaInfoList;
		//拼接查询条件
		String orgaIds ="''";
		for (Map<String, Object> orgaInfo:orgaInfoList) {
			if (orgaInfo.get("old_orgaId")!=null) {
				orgaIds = orgaIds + ",'" +orgaInfo.get("old_orgaId")+"'";
			}else {
				orgaIds = orgaIds + ",'" +orgaInfo.get("old_superorgaId")+"'";
			}
		}
		String sqlString = "SELECT DISTINCT(old_superorgaId)  FROM t_kfrh_orgainfo_gx_zhuijia WHERE old_orgaId in("+orgaIds+")";
		System.out.println(sqlString);
		jdbcUtil = new JdbcUtil();
		List<Map<String, Object>> superOrgaInfoList = jdbcUtil.queryForList(sqlString);
		if (!superOrgaInfoList.isEmpty()) {
			allOrgaInfoList.addAll(superOrgaInfoList);
			allOrgaInfoList.addAll(querySuperOrgaInfo(superOrgaInfoList));
		}
		return allOrgaInfoList;
	}
}
